<template>
    <div style="margin-left: 20px">
        <el-row>
            <el-col :span="8">
                <span>项目编号：{{ projectInfo.projectCode }}</span>
            </el-col>
            <el-col :span="8">
                <span>项目名称：{{ projectInfo.projectName  }}</span>
            </el-col>
            <el-col :span="8">
                <span>采购类别：{{ projectInfo.categoryName }}</span>
            </el-col>
            <el-col :span="20" style="margin-top: 10px">
                <el-form label-position="left" label-width="90px" ref="projectInvitationInfo" :model="projectInvitationInfo" :rules="rules">
                    <el-col :span="12">
                        <el-form-item label="采购地点:" prop="inquiryPlace">
                            <el-input type="text" placeholder="请输入内容" size="small" v-model="projectInvitationInfo.inquiryPlace" style="width: 50%"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="截止时间:" prop="inquiryTime">
                            <el-date-picker
                                style="width: 50%;"
                                size="small"
                                format="yyyy-MM-dd HH:mm:ss"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                v-model="projectInvitationInfo.inquiryTime"
                                type="datetime"
                                placeholder="选择日期时间">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系人:" prop="contactPerson">
                            <el-input type="text" size="small" v-model="projectInvitationInfo.contactPerson" placeholder="请输入内容" style="width: 50%"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="联系电话:" prop="contactTel">
                            <el-input type="text" size="small" v-model="projectInvitationInfo.contactTel" placeholder="请输入内容" style="width: 50%" ></el-input>
                        </el-form-item>
                    </el-col>
                </el-form>
            </el-col>
            <!--          生成邀请函-->
            <el-col :span="24">
                <div>
                    <span>生成邀请函</span>
                    <el-button size="small" type="primary" style="margin-left: 10px" @click="createInvitation" :disabled="projectInfo.isSubmit === 1">生成邀请函</el-button>
                    <span style="margin-left: 10px;color: red;font-size: 10px" v-if="projectInfo.isSubmit === 1">成交供应商已提交，无法更改</span>
                </div>
                <div style="margin-top: 10px;margin-bottom: 10px" v-if="true">
                    <el-table
                            :data="invitationTable"
                            border
                            size="small"
                            style="width: 100%">
                        <el-table-column
                                prop="generateTime"
                                min-width="150px"
                                label="生成时间"
                        >
                        </el-table-column>
                        <el-table-column
                                prop="inquiryPlace"
                                min-width="150px"
                                label="采购地点"
                        >
                        </el-table-column>
                        <el-table-column
                                prop="inquiryTime"
                                min-width="150px"
                                label="采购时间"
                        >
                        </el-table-column>
                        <el-table-column
                                prop="contactPerson"
                                min-width="100px"
                                label="联系人">
                        </el-table-column>
                        <el-table-column
                                prop="contactTel"
                                min-width="130px"
                                label="联系电话">
                        </el-table-column>
                        <el-table-column
                                prop="supplierName"
                                min-width="170px"
                                label="供应商">
                        </el-table-column>
                        <el-table-column
                                prop="fileName"
                                min-width="250px"
                                label="文件名">
                        </el-table-column>
                        <el-table-column
                                width="120px"
                                label="操作"
                        >
                            <template slot-scope="{$index,row}">
                                <el-button type="text" style="text-align: center;margin-left: 7px" @click="downloadInvitation(row)">下载</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-col>
<!--            上传盖章文件-->
            <el-col :span="24">
                <span style="margin-top: 10px">上传签章后的邀请函</span>
                <div v-if="projectInfo.isArchive === 0">
                    <div style="margin-top: 20px">
                        <span>请先选择供应商：</span>
                        <el-select style="width: 150px;margin-left: 10px" size="small" v-model="supplierNameTwo" placeholder="请选择">
                            <el-option
                                v-for="item in supplierNameList"
                                :key="item.id"
                                :label="item.supplierName"
                                :value="item.supplierName">
                            </el-option>
                        </el-select>
                        <el-button size="small" style="margin-left: 7px" @click="supplierNameTwo = '' ">清除选择</el-button>
                    </div>
                    <div style="margin-top: 10px">
                        <el-upload style="margin-left: 10px;display: inline"
                                   :show-file-list="false"
                                   :headers='token'
                                   :action="uploadUrl + supplierNameTwo"
                                   ref="upload"
                                   accept=".pdf"
                                   :on-success="handleSuccess"
                                   :on-progress="progress"
                                   :on-error="fileError"
                                   v-loading.fullscreen.lock="loading"
                                   :element-loading-text="progressPercentTitle"
                                   element-loading-spinner="el-icon-loading"
                                   element-loading-backgroud="rgba(0,0,0,0.1)"
                                   v-if="supplierNameTwo"
                                   :before-upload="beforeUpload"
                        >
                            <el-button size="small" type="primary">上传盖章后的邀请函</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传pdf文件，且不超过200Mb</div>
                        </el-upload>
                    </div>
                </div>
                <div v-else>
                    <span>盖章文件列表(<span style="color: red">归档提交后不能对文件在进行操作</span>)</span>
                </div>

                <div style="margin-top: 10px;margin-bottom: 10px" v-if="true">
                    <el-table
                        :data="invitationTagTable"
                        size="small"
                        border
                        style="width: 60%">

                        <el-table-column
                            prop="uploadTime"
                            min-width="130px"
                            label="上传时间">
                        </el-table-column>
                        <el-table-column
                            prop="supplierName"
                            min-width="170px"
                            label="供应商名称">
                        </el-table-column>
                        <el-table-column
                            prop="filename"
                            min-width="170px"
                            label="文件名称">
                        </el-table-column>
                        <el-table-column
                            width="120px"
                            label="操作"
                        >
                            <template slot-scope="{$index,row}">
                                <el-button type="text" style="text-align: center;margin-left: 7px" @click="downLoadSteamed(row)">下载</el-button>
                                <el-button v-if="projectInfo.isArchive === 0" type="text" style="margin-left: 7px;color: red" @click="deleteInvitationStampedFile(row)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </el-col>
        </el-row>
    </div>

</template>

<script>


import {
    addInvitation, deleteInvitationStamped,
    downloadInvitationFile,
    downloadStamped, getAllSuppliers,
    getInvitationTag,
    showInvitation
} from "@/api/shopping/invitation";
import {serverIp} from "../../../public/config";
import downloadFile from "@/utils/downloadFile";

export default {
    props: {
        projectInfo: {
            type: Object,
            default () {
                return {}
            }
        },
        invitationTable: {
            type: [],
            default() {
                return [];
            }
        },
        invitationTagTable: {
            type: [],
            default() {
                return [];
            }
        },
        supplierNameList:{
            type: [],
            default() {
                return [];
            }
        },

        required: true
    },
    data() {
        return {
            project: {},
            supplierNameTwo: "", // 供应商名字
            projectInvitationInfo:{
                inquiryPlace: "",
                inquiryTime: "",
                contactPerson: "",
                contactTel: ""
            },
            rules: {
                inquiryPlace:[{required: true, message: '请输入采购地点', pattern: '[^ \x22]+', trigger: 'blur'}],
                inquiryTime:[{required: true, message: '请输入采购时间',trigger: 'blur'}],
                contactPerson:[{required: true, message: '请输入联系人', pattern: '[^ \x22]+', trigger: 'blur'}],
                contactTel:[{required: true, message: '请输入联系人电话', pattern: '[^ \x22]+', trigger: 'blur'},{
                    validator: function(rule, value, callback) {
                        if (/^1[34578]\d{9}$/.test(value) == false) {
                            callback(new Error("手机号格式错误"));
                        } else {
                            callback();
                        }
                    },
                    trigger: "blur"
                }]
            },
            token: { Authorization:localStorage.getItem("token") },
            uploadUrl: `${serverIp}/invitation/upload/${this.projectInfo.projectId}/sb/`,
            loading: false,
            supplierNameList: [] ,// 供应商数组
            progressPercentTitle: "", // 展示百分比
            progressPercent: 0, // 进度
        }
    },
    mounted() {
        this.project = this.projectInfo
    },
    watch: {
        projectInfo: {
            // 监听数据发生变化的处理函数
            handler(newV) {
                this.project = JSON.parse(JSON.stringify(newV));//将监听到修改的值赋予到dataAttrs中
            },
            // 是否开启深度监听，由于我们上面props中是一个Object对象，所以需要开启深度监听功能
            deep: true
        }
    },
    methods: {
        async createInvitation() {
            this.$loading({
                fullscreen: true,
            });
            // console.log(this.projectInvitationInfo)
            try {
                this.$refs.projectInvitationInfo.validate(async (valid) => {
                    if (valid) {
                        let theDate = {
                            projectId: this.projectInfo.projectId,
                            inquiryPlace: this.projectInvitationInfo.inquiryPlace,
                            inquiryTime: this.projectInvitationInfo.inquiryTime,
                            contactPerson: this.projectInvitationInfo.contactPerson,
                            contactTel: this.projectInvitationInfo.contactTel,
                        }
                        let res = await addInvitation(theDate);
                        if (res.data.code === 200) {
                            this.$message.success("生成成功")
                            this.$refs["projectInvitationInfo"].resetFields();
                            await this.getAllInvitation()
                        } else {
                            this.$message.error(res.data.msg)
                        }
                    }
                })
            } catch (e) {
                this.$message.error(e)
            } finally {
                this.$loading().close();
            }
        },
        async getAllInvitation(){
            let res = await showInvitation(this.project.projectId)
            if (res.data.code === 200){
                this.invitationTable = res.data.data;
            }else {
                this.$message.error(res.data.msg)
            }
        },

        // 文件上传之前钩子
        beforeUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 200;
            if (!isLt2M) {
                this.$message.error('上传文件大小大小不能超过 200MB!');
                return false;
            }
            if (file.type !== "application/pdf"){
                this.$message.error('上传文件必须是pdf');
                return false;
            }
        },
        // 上传文件时钩子
        progress(event,file,fileList){
            this.loading = true;
            this.progressPercent = Math.floor(event.percent);
            this.progressPercentTitle = "已上传" + this.progressPercent + "%"
        },
        fileError(){
            this.loading=false;
            this.$message.error("失败")
        },
        handleSuccess(){
            this.loading = false;
            // this.$message.success("上传成功")
            alert("上传成功！")
            // 清除选择的供应商
            this.supplierNameTwo = '';
            // 获得上传的文件
            this.getAllInvitationStamped();
            // 更新供应商
            this.getNoAllSupplier(this.project.projectId)
        },
        // 获得未上传的供应商
        async getNoAllSupplier(data){
            let res = await getAllSuppliers(data)
            if (res.data.code === 200){
                this.supplierNameList = res.data.data;
            }else {
                this.supplierNameList = [];
                this.$message.error(res.data.msg)
            }
        },
        // 获得上传盖章文件列表
        async getAllInvitationStamped(){
            let resTag = await getInvitationTag(this.project.projectId)
            if (resTag.data.code === 200){
                this.invitationTagTable = resTag.data.data;
            }else {
                this.$message.error(resTag.data.msg)
            }
        },
        async downloadInvitation(row){
            let res = await downloadInvitationFile(row.id)
            downloadFile(res,row.fileName)
        },

        async downLoadSteamed(row){
            let res = await downloadStamped(row.id)
            downloadFile(res,row.filename)
        },
        // 删除盖章的邀请函
        async deleteInvitationStampedFile(row){
            this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async() => {
                let res =await deleteInvitationStamped(row.id)
                if(res.data.code==200){
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                    await this.getAllInvitationStamped()
                    // 更新未上传的供应商
                    await this.getNoAllSupplier(this.project.projectId)
                }else {
                    this.$message.error(res.data.msg)
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        }

    }
}

</script>

<style scoped>

</style>
